import React, { useState, useEffect } from 'react'
import { Input, Form, message } from 'antd'
import { ModalForm } from '@ant-design/pro-form';
import TreeTransfer from '@/components/TreeTransfer'
import { addDevice } from '@/services/group';

export default (props) => {

    const { group: { detail }, unit: { formatUnitAndUserList } } = props


    const deviceList = detail.device || []

    var checkedKeys = deviceList.filter(item => (item.deviceSn != '')).map(item => item.deviceSn)
    
    const [targetKeys, setTargetKeys] = useState([])

    const onChangeTransfer = (keys) => {
        setTargetKeys(keys)
    }

    // 添加群组成员
    const saveAddDevice = async (values) => {
        const result = await addDevice({
            groupId: detail.id,
            ...values
        })
        if (result.code === 0) {
            message.success("群组成员添加成功")
            props.onCancel()
            props.callback()
        } else {
            message.error("群组成员添加失败")
        }
    }

    return (
        <ModalForm title="添加群组成员"
            visible={props.visible}
            width={600}
            modalProps={{
                destroyOnClose: true,
                onCancel: props.onCancel,
            }}
            onFinish={async (values) => {
                saveAddDevice(values)
            }}
            initialValues={{
                groupName: detail.groupName || ''
            }}
        >
            <Form.Item
                label="群组名称"
                name="groupName"
                rules={[{ required: true, message: '请输入群组名称!' }]}
            >
                <Input placeholder="请输入群组名称" disabled={true} />
            </Form.Item>
            <Form.Item name="device[]" label="群组成员">
                <TreeTransfer
                    titles={['组织机构', '群组成员']}
                    targetKeys={targetKeys.length ? targetKeys : checkedKeys}
                    onChange={onChangeTransfer}
                    dataSource={formatUnitAndUserList}
                />
            </Form.Item>
        </ModalForm>
    )
}